<template>
  <el-dialog
    title="产业政策"
    top="30px"
    width="800px"
    :visible.sync="visible"
    :before-close="beforeClose"
    :close-on-click-modal="false"
  >
    <div class="mb-3">
      <el-button
        type="primary"
        icon="el-icon-upload2"
        plain
        :loading="uploadLoading"
        @click="handlePolicyPick"
      >
        上传产业政策
      </el-button>
      <input
        type="file"
        name="file"
        class="el-upload__input"
        multiple="multiple"
        ref="input"
        @change="handlePolicyChange"
      />
    </div>
    <c-table border v-loading="loading" :stripe="false" :columns="tableColumns" :data="tableData">
      <template v-slot:policy_name="scope">
        <a :href="scope.row.policy_url" target="_blank">{{ scope.row.policy_name }}</a>
      </template>
    </c-table>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { stringFileName } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      loading: false,
      params: {},
      order: {
        create_time: 'desc',
      },
      tableName: 'industrial_package_policy',
      tableData: [],
      tableColumns: [
        { attrs: { label: '序号', type: 'index', align: 'center' } },
        {
          attrs: { label: '产业政策名称', prop: 'policy_url' },
          slot: 'policy_name',
        },
        {
          attrs: { label: '操作', align: 'center', width: 80 },
          operations: [{ content: '删除', icon: 'fa fa-trash', event: this.handleDelete }],
        },
      ],
      uploadLoading: false,
    }
  },
  computed: {
    ...mapGetters(['user', 'clientId']),
    goodsId() {
      return this.formData.industrial_package_id
    },
    uploadDir() {
      return `credit/goods/${this.formData.load_name || ''}`
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.getData()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    async getData() {
      if (!this.goodsId) return

      this.params['industrial_package_id.eq'] = this.goodsId
      this.params['submit_client_id.eq'] = this.clientId

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.params, this.order)
      )
      this.loading = false

      this.tableData = ((res && res.data) || []).map(item => {
        item.policy_name = stringFileName(item.policy_url)
        return item
      })
    },
    handlePolicyPick() {
      this.$refs.input.value = null
      this.$refs.input.click()
    },
    async handlePolicyChange(e) {
      const { files } = e.target
      if (!files || !files.length) return

      try {
        this.uploadLoading = true
        const paths = await this.uploadPolicyFile(Array.prototype.slice.call(files))
        const res = await this.addData(paths)

        this.$emit('success', res)
        this.$message.success('上传成功')
        this.getData()
      } catch (e) {
        console.error(e)
        this.$message.error('上传失败，请重试！')
      } finally {
        this.uploadLoading = false
      }
    },
    signature() {
      return this.$http.post(`/auth/signature/?userDir=${this.uploadDir}`).then(res => {
        const sts = res.data || {}
        sts.expire = Number.parseInt(sts.expire, 10)
        sts.OSSAccessKeyId = sts.accessid
        return sts
      })
    },
    async uploadPolicyFile(files) {
      const sts = await this.signature()
      const uploadApis = []
      for (const file of files) {
        uploadApis.push(this.uploadFile(sts, file))
      }
      return Promise.all(uploadApis)
    },
    uploadFile(sts, file) {
      const formData = new FormData()
      Object.keys(sts).forEach(key => {
        formData.append(key, sts[key])
      })
      const key = `${this.uploadDir}/${file.name}`
      formData.append('key', key)
      formData.append('file', file, file.name)
      formData.append('success_action_status', 200)

      const host = `${sts.host}.aliyuncs.com`
      return this.$http.post(host, formData).then(() => `${host}/${key}`)
    },
    addData(paths) {
      return this.$api.addBatch(
        this.$serviceName,
        this.tableName,
        paths.map(path => ({
          address_code: this.user.queryAddressCode,
          submit_client_id: this.clientId,
          industrial_package_id: this.goodsId,
          policy_url: path,
        }))
      )
    },
    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: '确定删除？',
          type: 'warning',
          beforeClose: () => this.$api.deleteData(this.$serviceName, this.tableName, row.id),
        })
        .then(res => {
          this.$emit('success', res)
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
  },
}
</script>

<style lang="scss" scoped></style>
